package com.yww.datastructure.heap;

import java.util.Arrays;
import java.util.Iterator;

/**
 * @author yww
 * @description 大顶堆
 * @since 2024/2/7 15:29
 */
public final class MaxHeap implements IHeap {
    int[] array;
    int size;

    public MaxHeap(int[] array) {
        this.array = array;
        this.size = array.length;
        heapify(); // 堆化
    }

    public MaxHeap(int capacity) {
        this.array = new int[capacity];
    }

    @Override
    public int peek() {
        return array[0];
    }

    @Override
    public int poll() {
        int polled = array[0];
        swap(0, --size);
        down(0);
        return polled;
    }

    @Override
    public int poll(int index) {
        int polled = array[index];
        swap(index, --size);
        down(index);
        return polled;
    }

    @Override
    public void replace(int replaced) {
        array[0] = replaced;
        down(0);
    }

    @Override
    public boolean offer(int offered) {
        if (isFull()) {
            return false;
        }
        up(offered);
        size++;
        return true;
    }

    /**
     * 堆排序（大顶堆）算法描述
     * 1. heapify建立大顶堆
     * 2. 将堆顶与堆底交换（最大元素被交换到堆低），缩小并下潜调整堆
     * 3. 重复第二步直至堆里剩一个元素
     *
     * @return 排序结果
     */
    @Override
    public int[] sort() {
        int tempSize = size;
        int[] tempArr = Arrays.copyOf(this.array, array.length);
        while (size > 1) {
            swap(0, --size);
            down(0);
        }
        int[] returnArr = this.array;
        this.array = tempArr;
        this.size = tempSize;
        return returnArr;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    @Override
    public boolean isFull() {
        return size == array.length;
    }

    @Override
    public Iterator<Integer> iterator() {
        return new Iterator<Integer>() {
            int i = 0;

            @Override
            public boolean hasNext() {
                return i < size;
            }

            @Override
            public Integer next() {
                return array[i++];
            }
        };
    }

    /**
     * 堆：建堆
     * 从最后一个子树下潜（非叶子节点）
     */
    private void heapify() {
        for (int i = size / 2 - 1; i >= 0; i--) {
            down(i); // 从最后一个子树下潜（非叶子节点）
        }
    }

    /**
     * 堆：上浮方法
     * 将 offered 元素上浮: 直至 offered 小于父元素或到堆顶
     */
    private void up(int offered) {
        int child = size;
        while (child > 0) {
            int parent = (child - 1) / 2;
            if (offered > array[parent]) { // 新元素大，上浮
                array[child] = array[parent];
            } else {
                break;
            }
            child = parent;
        }
        array[child] = offered;
    }

    /**
     * 堆：下潜方法
     * 将父下潜，直至父比子大
     */
    private void down(int parent) {
        if (parent >= size) {
            return;
        }
        int max = parent;
        int left = parent * 2 + 1; // 左孩子
        int right = left + 1; // 右孩子

        if (left < size && array[max] < array[left]) {
            max = left; // 左孩子大
        }
        if (right < size && array[max] < array[right]) {
            max = right; // 右孩子大
        }
        if (max != parent) {
            swap(max, parent); // 将大的交换到parent
            down(max);
        }
    }

    private void swap(int i, int j) {
        int temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
}
